<template>
  <div id="Content-page">
    <Paging :pagData="[{ name: '商品管理', router: '/product' }]" />
    <div class="content-main">
      <div class="global-display subbuttom">
        <el-button type="primary" @click="addGoods">新增商品</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="商品图片">
          <template #default="scope">
            <el-image style="width: 40px; height: 40px; border-radius: 5px" :src="scope.row.image" fit="cover"
              :preview-src-list="[scope.row.image]" preview-teleported />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="category" label="所属类目">
          <template #default="scope">
            <span>{{ scope.row.category.categoryName }}</span></template>
        </el-table-column>
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="stock" label="库存" />
        <el-table-column prop="saleNum" label="销量" />
        <el-table-column prop="label" label="标签">
          <template #default="scope">
            <el-tag size="default" v-for="label1 in scope.row.label" :key="label1">{{ label1 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" size="default" @click="edit(scope.row._id, scope.$index)">编辑</el-button>
            <el-button type="danger" size="default" @click="deleteGoods(scope.row._id, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination class="pager-next" background layout="prev, pager, next" :total="pager.total" hide-on-single-page
      @current-change="currentChanges" @size-change="sizeChange" />
  </div>

  <!-- 新增商品 -->
  <el-drawer :key="drawer" v-model="drawer" size="600px" title="新增商品">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="商品类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio :value="1">一般商品</el-radio>
          <el-radio :value="2">小料</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择分类">
          <el-option v-for="item in options" :key="item._id" :label="item.categoryName" :value="item._id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品图片" prop="image">
        <UploadImg width="100px" :uploadImgurl="form.image" />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" placeholder="填写商品名称" />
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input type="textarea" v-model="form.description" placeholder="填写商品描述" />
      </el-form-item>
      <div v-if="form.type === 1">
        <el-form-item label="属性设置" prop="attribute">
          <el-tree style="width: 600px" :default-checked-keys="form.checkedkeys" v-if="form.attribute.length"
            :data="form.attribute" show-checkbox node-key="_id" @check="changeCheck" ref="treeRef">
            <template #default="{ node, data }">
              <div style="flex:1" class="flex-between">
                <div class="rem_label">
                  <span>{{ data.label }}</span>
                  <span v-if="node.level === 2 && data.recommend" class="reommend_text">荐</span>
                  <span style="padding-left: 10px;color: #47a8dd;" v-if="data.addPrice">+{{ data.addPrice }}</span>
                </div>
                <el-button v-if="node.level === 2 && node.checked" link type="primary"
                  @click="setAttribute(data, node)">设置</el-button>
              </div>
            </template>
          </el-tree>
          <el-button v-else @click="$router.push('/category-params')">请先添加商品属性</el-button>
        </el-form-item>
        <!-- 从商品列表获取小料 -->
        <el-form-item label="小料" prop="small">
          <el-select v-model="form.small" multiple placeholder="请选择小料">
            <el-option v-for="item in smallOptions" :key="item._id" :label="item.name" :value="item._id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否推荐"><el-switch v-model="form.recommend"></el-switch></el-form-item>
      </div>
      <el-form-item label="商品价格" prop="price"> <el-input-number v-model="form.price" :min="0" /> </el-form-item>
      <el-form-item label="商品库存" prop="stock"> <el-input-number v-model="form.stock" :min="0" /> </el-form-item>
      <el-form-item><el-button type="primary" @click="submit(formRef)">提交</el-button></el-form-item>
    </el-form>
  </el-drawer>
  <el-dialog v-model="settingDialog" :title="settingTips">
    <el-form ref="settingRef" :form="settingForm">
      <el-form-item label="推荐"><el-switch v-model="settingForm.recommend"></el-switch></el-form-item>
      <el-form-item label="加价"><el-input-number v-model="settingForm.addPrice" :min="0" /></el-form-item>
      <el-form-item><el-button type="primary" @click="settingSubmit">提交</el-button></el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
// 顶部导航组件
import Paging from "@/page/component/Paging-component.vue";
import UploadImg from "@/page/component/upload.vue";
import { ref, onMounted, reactive, nextTick } from "vue";
import { useRouter } from "vue-router";
import emitter from "@/api/event.js";
const $router = useRouter(); // 这是路由跳转的
import request from "@/api/request.js";
const formRef = ref();
// 表格数据
const tableData = ref([]);
const drawer = ref(false)
const settingDialog = ref(false)
const settingTips = ref("")
const rules = reactive({
  categoryId: [{ required: true, message: '请选择商品分类', }],
  image: [{ required: true, message: '请上传商品图片', }],
  name: [{ required: true, message: '请输入商品名称', }],
  description: [{ required: true, message: '请输入商品描述', }],
})
const settingForm = reactive({
  recommend: false, addPrice: 0, data: {}, node: {}
})
const checkedKeys = ref([]);
// const dataSource = ref([])
const smallOptions = ref([])
const treeRef = ref()
const settingRef = ref()
// 商品分类
const options = ref([]);
const form = reactive({
  _id: "", type: 1, categoryId: "", checkedkeys: [], image: "", name: "", attribute: [], description: "", small: [], price: 0, stock: 0
})
const pager = reactive({
  page: 1, total: 20, total: 0
})
let initialTreeData = [];
// 获取商品
onMounted(() => {
  requestApi();
});
async function requestApi() {
  request.get("/getGoodsList", {
    page: pager.page,
    size: pager.size,
  }).then(res => {
    tableData.value = res.data.list;
    pager.total = res.data.total;
    smallOptions.value = res.data.smallList;
  })


  request.get("/getSkuParams").then(res => {
    // dataSource.value = res.data;
    initialTreeData = JSON.parse(JSON.stringify(res.data));
    console.log(initialTreeData);
  })
  request.get("/getAllCategory").then(res => {
    options.value = res.data;
  })
}
emitter.on("upload-image-Success", (res) => {
  form.image = res.url;
  formRef.value?.validateField("image")
});
const addGoods = () => {
  drawer.value = true;
  form._id = undefined;
  form.attribute = initialTreeData;
}
const setAttribute = (data, node) => {
  settingDialog.value = true;
  settingForm.data = data;
  settingForm.node = node;
  settingRef.value?.resetFields();
  settingForm.recommend = data.recommend || false;
  settingForm.addPrice = data.addPrice || 0;
  settingTips.value = node.parent.data.label + " - " + data.label;

}
// 分页
async function currentChanges(event) {
  pager.page = event;
  requestApi();
}
async function sizeChange(event) {
  pager.size = event;
  requestApi();
}
// 删除商品
import { ElMessage, ElMessageBox } from "element-plus";
function deleteGoods(id, index) {
  ElMessageBox.confirm("确定删除该商品吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    center: true,
  }).then(async () => {
    await request.delete("/delGoods/" + id);
    tableData.value.splice(index, 1);
  });
}
const edit = (_id, index) => {
  drawer.value = true;
  Object.assign(form, {})
  Object.assign(form, tableData.value[index])
  console.log("推荐商品", form, tableData.value[index]);
}
const filterNode = (value, data) => {

  if (!value) return true
  return data.label.includes(value)
}
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (form.type === 1) {
        for (let i = 0; i < form.attribute.length; i++) {
          const item = form.attribute[i];
          if (checkedKeys.value.includes(item._id)) {
            if (!item.recommend) {
              return ElMessage.error(`${item.label}缺乏推荐属性`)
            } else if (item.minAddPrice) {
              return ElMessage.error(`${item.label}缺乏与商品价格匹配的sku`)
            }
          }
        }
      }
      form.checkedkeys = treeRef.value.getCheckedKeys();
      console.log(form.checkedkeys);
      request.post("/addGoods", form).then((res) => {
        request.get("/getGoodsList", {
          page: pager.page,
          size: pager.size,
        }).then(res => {
          tableData.value = res.data.list;
          pager.total = res.data.total;
          smallOptions.value = res.data.smallList;
        })
        drawer.value = false;
      })

    } else {
      console.log("error submit!", fields);
    }
  });
}
const settingSubmit = () => {
  settingForm.data.addPrice = settingForm.addPrice;
  settingForm.node.parent.data.children.forEach(item => item.recommend = false)
  settingForm.data.recommend = settingForm.recommend;
  settingForm.node.parent.data.recommend = true;
  let rice = settingForm.addPrice;
  settingForm.node.parent.data.minAddPrice = settingForm.addPrice;
  if (settingForm.addPrice != 0) {

    const filterdata = Array.from(settingForm.node.parent.childNodes).filter(item => item.checked);
    // rice = filterdata[0].addPrice || 0;
    console.log(settingForm.node.parent.data.minAddPrice, filterdata);
    filterdata.forEach(item => rice = Math.min(rice, item.data.addPrice || 0))
    settingForm.node.parent.data.minAddPrice = rice;
  }
  settingDialog.value = false;
}

const changeCheck = (data, node) => {
  checkedKeys.value = node.checkedKeys.concat(node.halfCheckedKeys)
}
</script>

<style>
.rem_label {
  position: relative;
}

.rem_label .reommend_text {
  position: absolute;
  color: red;
  top: 2px;
  right: -15px;
  line-height: 20px;
  font-size: 12px;
}
</style>
